package com.spring.theory.bean.scope;

import com.spring.theory.bean.scope.type.BeanOfApplication;
import com.spring.theory.bean.scope.type.BeanOfPrototype;
import com.spring.theory.bean.scope.type.BeanOfRequest;
import com.spring.theory.bean.scope.type.BeanOfSession;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Bean对象范围
 * <p>
 * - 没加scope注解，默认是单例
 *
 * @author H
 * @version 1.0
 * @date 2023-12-27 14:53
 */
@RestController
public class ScopeController {

    @Resource
    private ApplicationContext applicationContext;
    @Lazy
    @Resource
    private BeanOfPrototype beanForPrototype;
    //单例使用其它域的bean，加lazy注解避免bean的scope失效
    @Lazy
    @Autowired
    private BeanOfRequest beanForRequest;
    @Lazy
    @Autowired
    private BeanOfSession beanForSession;
    @Lazy
    @Autowired
    private BeanOfApplication beanForApplication;

    @GetMapping(value = "/test", produces = "text/html")
    public String test(HttpServletRequest request, HttpSession session) {
        //BeanOfPrototype使用lazy注解；每次由代理创建新的对象
        ScopeController bean = applicationContext.getBean(ScopeController.class);
        BeanOfPrototype beanForPrototype1 = bean.beanForPrototype;
        BeanOfPrototype beanForPrototype2 = bean.beanForPrototype;
        BeanOfPrototype beanForPrototype3 = bean.beanForPrototype;
        // 设置 session 过期时间为 10 秒
        session.setMaxInactiveInterval(10);
        return "<ul>" +
                "<li>request scope: " + beanForPrototype1 + "==" + beanForPrototype2 + "==" + beanForPrototype3 + "</li>" +
                "<li>request scope: " + beanForRequest + "</li>" +
                "<li>session scope: " + beanForSession + "</li>" +
                "<li>application scope: " + beanForApplication + "</li>" +
                "</ul>";
    }

}
